import Foundation
import UserNotifications

private final class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // 在前台时也显示横幅和声音
        completionHandler([.banner, .sound])
    }
}

enum NotificationService {
    private static var delegate: NotificationDelegate?
    /// 请求通知权限并在工作日 11:59 安排本地提醒
    static func requestAuthorizationAndScheduleLunchReminders() {
        let center = UNUserNotificationCenter.current()
        // 设置代理，确保前台也能显示通知
        let del = NotificationDelegate()
        delegate = del
        center.delegate = del
        center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
            if let error = error {
                print("❌ [Notification] 请求授权失败: \(error.localizedDescription)")
                return
            }
            if granted {
                print("✅ [Notification] 已获得通知授权")
                scheduleWeekdayLunchReminders()
            } else {
                print("⚠️ [Notification] 用户未授权通知")
            }
        }
    }

    /// 取消并重新安排工作日午餐提醒
    private static func scheduleWeekdayLunchReminders() {
        let center = UNUserNotificationCenter.current()
        let identifiers = (2...6).map { "lunch_reminder_weekday_\($0)" } // Monday=2 ... Friday=6
        // 清理旧的同名请求，避免重复
        center.removePendingNotificationRequests(withIdentifiers: identifiers)

        let content = UNMutableNotificationContent()
        content.title = "午餐提醒"
        content.body = "朋友们，马上吃饭喽，大家记得带上耳机记录噢[嘿哈]"
        content.sound = .default

        for weekday in 2...6 { // 周一到周五
            var components = DateComponents()
            components.weekday = weekday
            components.hour = 11
            components.minute = 59

            let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
            let request = UNNotificationRequest(
                identifier: "lunch_reminder_weekday_\(weekday)",
                content: content,
                trigger: trigger
            )
            center.add(request) { error in
                if let error = error {
                    print("❌ [Notification] 安排失败(weekday=\(weekday)): \(error.localizedDescription)")
                } else {
                    print("📌 [Notification] 已安排 周\(weekday) 11:59 午餐提醒")
                }
            }
        }
    }
}
